package com.example.gateway.filter;

import com.example.common.util.JWTUtil;
import io.netty.util.internal.StringUtil;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static com.example.gateway.util.AuthResultUtil.buildResult;

/**
 * @author benjamin_5
 * @Description
 * @date 2023/2/15
 */
//@Component
@AllArgsConstructor
public class AuthFilter implements Ordered, GlobalFilter {

    // 路径匹配器
    private final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    // 跳过token校验的url
    static List<String> skipUrlList = Arrays.asList("/user-server/login/*","/error/*","/user-server/auth/token/*");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        // url是否跳过token校验
        String url = exchange.getRequest().getURI().getPath();
        if(isSkip(url)){
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        // 判断token是否为空
        if(StringUtil.isNullOrEmpty(token)){
            return unAuth(response,"token为空");
        }
        // token是否合法
        if(!token.startsWith(JWTUtil.SEPARATOR)){
            return unAuth(response, "token不合法");
        }
        // token是否过期
        if(JWTUtil.isExpiration(token)){
            return unAuth(response, "token已过期");
        }
        String userId = JWTUtil.getUserId(token);
        if(StringUtil.isNullOrEmpty(userId)){
            return unAuth(response, "token不合法");
        }
        return chain.filter(exchange);
    }

    private Mono<Void> unAuth(ServerHttpResponse response, String message){
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 声明响应数据的格式为json
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        String result = buildResult(HttpStatus.UNAUTHORIZED.value(), message);
        DataBuffer wrap = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(wrap));
    }

    /**
     * url是否在要跳过校验的链接集合中
     * @param url
     * @return
     */
    private boolean isSkip(String url){
         return skipUrlList.stream().anyMatch(pattern -> PATH_MATCHER.match(pattern, url));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
